
package com.shop.cloud.controller.hongfu;


import io.swagger.annotations.ApiOperation;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;

import com.shop.cloud.JPush.MsgPushUtils;
import com.shop.cloud.dao.hongfu.GoodsCategoryDao;
import com.shop.cloud.dao.hongfu.GoodsDao;
import com.shop.cloud.dao.hongfu.ShopDao;
import com.shop.cloud.dao.hongfu.ShopImageDao;
import com.shop.cloud.dao.hongfu.WithdrawConfigDao;
import com.shop.cloud.dao.hongfu.WithdrawHistoryDao;
import com.shop.cloud.domain.hongfu.BankAccount;
import com.shop.cloud.domain.hongfu.Goods;
import com.shop.cloud.domain.hongfu.GoodsAndShops;
import com.shop.cloud.domain.hongfu.GoodsCategory;
import com.shop.cloud.domain.hongfu.GoodsImage;
import com.shop.cloud.domain.hongfu.GoodsProduct;
import com.shop.cloud.domain.hongfu.ListToMap;
import com.shop.cloud.domain.hongfu.Message;
import com.shop.cloud.domain.hongfu.ProductSpec;
import com.shop.cloud.domain.hongfu.ProductSpec2;
import com.shop.cloud.domain.hongfu.Shop;
import com.shop.cloud.domain.hongfu.ShopImage;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.domain.hongfu.WithdrawConfig;
import com.shop.cloud.domain.hongfu.WithdrawHistory;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.filter.IgnoreAuth;
import com.shop.cloud.model.response.ObjectDataResponse;
import com.shop.cloud.service.hongfu.GoodsProductService;
import com.shop.cloud.service.hongfu.WithdrawConfigService;
import com.shop.cloud.service.hongfu.impl.BankAccountService;
import com.shop.cloud.service.hongfu.impl.GoodsImageService;
import com.shop.cloud.service.hongfu.impl.GoodsService;
import com.shop.cloud.service.hongfu.impl.MessageService;
import com.shop.cloud.service.hongfu.impl.UserService;
import com.shop.cloud.service.hongfu.impl.WithdrawHistoryService;
import com.shop.cloud.util.Page;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

/**
 * api
 * @author mengxiangdong
 */
@RestController	
@RequestMapping("api")
public class GoodsController {

	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsDao goodsDao;
	
	@Autowired
    private GoodsProductService goodsProductService;
	
	@Autowired
	private GoodsImageService goodsImageService;
	
	@Autowired
	private GoodsCategoryDao goodsCategoryDao;
	
	@Autowired
	private ShopDao shopDao;
	
	@Autowired
	private ShopImageDao shopImageDao;
	
	@Autowired
	private WithdrawHistoryService withdrawHistoryService;
	

	@Autowired
	private WithdrawConfigService withdrawConfigService;
	
	@Autowired
	private BankAccountService bankAccountService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private WithdrawConfigDao withdrawConfigDao;
	
	@Autowired
	private WithdrawHistoryDao withdrawHistoryDao;
	
	Logger logger = Logger.getLogger(GoodsController.class);
	
	@IgnoreAuth
	@ApiOperation(value = "查询总商品列表", notes = "查询总商品列表")
	@RequestMapping(value = "/queryGoods", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<Goods>> queryGoods(@RequestBody Goods goods) {
		
		if (goods==null) {
			return new ObjectDataResponse<Page<Goods>>(null);
		}
		
		//根据价格排序
	    if (goods.getIsPrice() !=null) {
			
		  if (goods.getIsPrice()==1) {
						goods.setOrderBy("GOODS.price desc");
		  }
		  if (goods.getIsPrice()==2) {
						goods.setOrderBy("GOODS.price asc");
		  }
		}
		
		//根据好评率排序
		if(goods.getIsReview()!=null){
			if (goods.getIsReview()==1) {
				goods.setOrderBy("GOODS.review desc");
			}
			if (goods.getIsReview()==2) {
				goods.setOrderBy("GOODS.review asc");
			}
		}
		
		//根据销量排序
		if(goods.getIsSold()!=null){
			if (goods.getIsSold()==1) {
				goods.setOrderBy("GOODS.sold_count desc");
			}
			if (goods.getIsSold()==2) {
				goods.setOrderBy("GOODS.sold_count asc");
			}
		}
		//综合排序
		if(goods.getIsAll()!=null){
			if (goods.getIsAll()==1) {
				goods.setOrderBy("GOODS.sold_count desc,GOODS.review desc,GOODS.price desc ");
			}
		}
		
		if (goods.getType()==0) {
			goods.setType(null);
			Page<Goods> datas = goodsService.apiPage(goods);
			return new ObjectDataResponse<Page<Goods>>(datas);
		}
		
		Page<Goods> datas = goodsService.apiPage(goods);
		return new ObjectDataResponse<Page<Goods>>(datas);
	}
	
	
	@IgnoreAuth
	@ApiOperation(value = "商品详情", notes = "商品详情")
	@RequestMapping(value = "/queryGoodsOne", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Goods> queryGoodsOne(@RequestBody Goods goods) throws JSONException {
		
		if (StringUtils.isBlank(goods.getId().toString())) {
			return new ObjectDataResponse<Goods>(null);
		}
		
	    Goods goods2=goodsService.get(goods.getId());
	    //图片信息
	    GoodsImage goodsImage=new GoodsImage();
	    goodsImage.setGoodsId(goods.getId());
	    List<GoodsImage> goodsImageList=goodsImageService.find(goodsImage);
	    goods2.setGoodsImages(goodsImageList);
	    
	    
        if (goods2.getIsSpecialPrice()==1) {
	    	
	    	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date = df.format(new Date());
			Timestamp.valueOf(date);
			long now=new Date().getTime();
			if(goods2.getSpecialStartTime()!=null){
				if (now>goods2.getSpecialStartTime().getTime() && now<goods2.getSpecialEndTime().getTime() ) {
					goods2.setPrice(goods2.getSpecialPrice());
					
				}
			}
		}
  
	    //规格信息
	    GoodsProduct goodsProduct=new GoodsProduct();
	    goodsProduct.setGoodsId(goods.getId());
	    List<GoodsProduct> goodsProductList=goodsProductService.find(goodsProduct);
	    List<GoodsProduct> goodsProductList2=new ArrayList<GoodsProduct>();
	   
	    for (int i = 0; i < goodsProductList.size(); i++) {
	    	if (StringUtils.isBlank(goodsProductList.get(i).getSpecs())) {
	    		
	    		if (goods2.getIsSpecialPrice()==1) {
		    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
					String date = df.format(new Date());
					Timestamp.valueOf(date);
					long now=new Date().getTime();
					if(goods2.getSpecialStartTime()!=null){
						if(now>goods2.getSpecialStartTime().getTime() && now<goods2.getSpecialEndTime().getTime()){
			    			for (int j = 0; j < goodsProductList.size(); j++) {
				    			goodsProductList.get(j).setPrice(goods2.getSpecialPrice());;
							}
			    		}
					}
			    }
	    		 
	    	   goods2.setGoodsProduct(goodsProductList);
	    	   return new ObjectDataResponse<Goods>(goods2);
	    	}
		}
	    
		ListToMap mm = new ListToMap();
		int k=0;
	    for (int i = 0; i < goodsProductList.size(); i++) {
	    	 List<ProductSpec> specList=new ArrayList<ProductSpec>();
	    	  JSONObject object=new JSONObject(goodsProductList.get(i).getSpecs());
	    	  Iterator<String> sIterator = object.keys(); 
	    	  GoodsProduct goodsProduct2=goodsProductList.get(i);
		    	 while(sIterator.hasNext()){
		    		 
		    		  ProductSpec spec=new ProductSpec();
		    	      String key = sIterator.next();
		    	      String value = object.getString(key);  
		    	
			    	  spec.setName(key);
			    	  spec.setValue(value.trim());
		    	    
		    	      specList.add(spec);
		    	 }  
		    	 goodsProduct2.setSpecs("");
		    	 goodsProduct2.setSpecsList(specList);
		    	 goodsProductList2.add(goodsProduct2);
		    	 
		    	 
		        for (int j = 0; j < specList.size(); j++) {
		        	ProductSpec sku=specList.get(j);
					mm.createClass(sku.getName(), k+++"",sku.getValue().trim());
				}
		    	 
		}
	    
		Map<String,List> map=mm.getAll();
		List<ProductSpec> sList=new ArrayList<ProductSpec>();
		for (String key : map.keySet()) {
			ProductSpec s=new ProductSpec();
			System.out.println("key= "+ key + " and value= " + map.get(key));
			s.setName(key);
			s.setValue(map.get(key).toString().trim());
			sList.add(s);
		}

		List<ProductSpec2> sList2=new ArrayList<ProductSpec2>();
		for (int i = 0; i < sList.size(); i++) {
			ProductSpec sp=sList.get(i);
			ProductSpec2 sp2=new ProductSpec2();
			String str2=sp.getValue().replace("[", "");
			String str3=str2.replace("]", "");
			
			String[] test1=str3.split(","); 
	        ArrayList list=new ArrayList(); 
	        for(int j=0;j<test1.length;j++){ 
	             if(!list.contains(test1[j].trim())) 
	             list.add(test1[j].trim());       
	        } 
	        sp2.setName(sp.getName());
	        sp2.setValue(list);
	        sList2.add(sp2);
		}
		goods2.setGoodsProduct2(sList2);
	    goods2.setGoodsProduct(goodsProductList2);
	    
	    if (goods2.getIsSpecialPrice()==1) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
			String date = df.format(new Date());
			Timestamp.valueOf(date);
			long now=new Date().getTime();
			if(goods2.getSpecialStartTime()!=null){
				if (now>goods2.getSpecialStartTime().getTime() && now<goods2.getSpecialEndTime().getTime() ) {
					goods2.setPrice(goods2.getSpecialPrice());
					for (int i = 0; i < goods2.getGoodsProduct().size(); i++) {
							goods2.getGoodsProduct().get(i).setPrice(goods2.getSpecialPrice());;
					}
				}
			}
	   }
	  
	   return new ObjectDataResponse<Goods>(goods2);
	}
	
	
	
	@IgnoreAuth
	@ApiOperation(value = "查询一级二级分类列表", notes = "查询一级二级分类列表")
	@RequestMapping(value = "/queryCategory", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<List<GoodsCategory>> queryCategory(@RequestBody GoodsCategory goodsCategory) {
		
		if (goodsCategory==null) {
			return new ObjectDataResponse<List<GoodsCategory>>(null);
		}
		
	    //一级
	    List<GoodsCategory> goodsCategoryList=goodsCategoryDao.queryCategory(goodsCategory);
	    
		//二级
		List<GoodsCategory> goodsCategoryListRes=new ArrayList<GoodsCategory>();
		for (int i = 0; i < goodsCategoryList.size(); i++) {
			GoodsCategory goodsCategoryT=goodsCategoryList.get(i);
			
			GoodsCategory goodsCategoryTwo=new GoodsCategory();
			goodsCategoryTwo.setParentId(goodsCategoryT.getId().intValue());
			List<GoodsCategory> goodsCategoryList2=goodsCategoryDao.queryCategoryTwo(goodsCategoryTwo);
			goodsCategoryT.setGoodsCategorys(goodsCategoryList2);
			
			goodsCategoryListRes.add(goodsCategoryT);
		}
		return new ObjectDataResponse<List<GoodsCategory>>(goodsCategoryListRes);
	}
	

	@IgnoreAuth
	@ApiOperation(value = "查询商品和商家列表", notes = "查询商品和商家列表")
	@RequestMapping(value = "/queryGoodsAndShops", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<GoodsAndShops> queryGoodsAndShops(@RequestBody Goods goods) {
		
		if (goods==null) {
			return new ObjectDataResponse<GoodsAndShops>(null);
		}
		GoodsAndShops goodsAndShops=new GoodsAndShops();

		//商品
		List<Goods> goodsList=goodsDao.queryGoodsByName(goods);
		List<Goods> goodsList2=new ArrayList<Goods>();
		for (int i = 0; i < goodsList.size(); i++) {
			  Goods good=goodsList.get(i);
			  GoodsImage goodsImage=new GoodsImage();
			  goodsImage.setGoodsId(goodsList.get(i).getId());
			  List<GoodsImage> goodsImageList=goodsImageService.find(goodsImage);
			  good.setGoodsImages(goodsImageList);
			  goodsList2.add(good);
		}
		  
		goodsAndShops.setGoodsList(goodsList2);
		
		//商家
		Shop shop=new Shop();
		shop.setName(goods.getName());
		List<Shop> shopList=shopDao.findByEntity(shop);
		List<Shop> shopList2=new ArrayList<Shop>();
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("status", 2);
		List<Shop> sList=shopDao.findMap(params);
		for (int i = 0; i < shopList.size(); i++) {
			Shop shop2=shopList.get(i);
			params.put("myLongitude", goods.getMyLongitude());
			params.put("myLatitude", goods.getMyLatitude());
			for (int j = 0; j < sList.size(); j++) {
				if (sList.get(j).getId().equals(shop2.getId())) {
					shop2.setDistance(sList.get(j).getDistance());
				}
			}
			
			ShopImage shopImage=new ShopImage();
			shopImage.setShopId(shop2.getId());
			 List<ShopImage> shopImageList=shopImageDao.findByEntity(shopImage);
			 if(shopImageList.size()>0){
				 shop2.setIcon(shopImageList.get(0).getImage());
			 }
			
			shopList2.add(shop2);
		}
		goodsAndShops.setShopList(shopList2);
	
		return new ObjectDataResponse<GoodsAndShops>(goodsAndShops);
	}
	
	
	@ApiOperation(value = "提现记录", notes = "提现记录")
	@RequestMapping(value = "/withList", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<WithdrawHistory>> withList(@CurrentUserId Long userId,@RequestBody WithdrawHistory withdrawHistory) {
		
		withdrawHistory.setUserId(userId);
		withdrawHistory.setOrderBy("WITHDRAW_HISTORY.create_time desc");
    Page<WithdrawHistory> data=withdrawHistoryService.page(withdrawHistory);
    
		return new ObjectDataResponse<Page<WithdrawHistory>>(data);
	}
	
	@ApiOperation(value = "所有提现记录", notes = "所有提现记录")
	@RequestMapping(value = "/allWithdrawHistoryList", method = RequestMethod.POST)
	@ResponseBody
	public ObjectDataResponse<Page<WithdrawHistory>> allWithdrawHistoryList(@CurrentUserId Long userId,@RequestBody WithdrawHistory withdrawHistory) {
		
	withdrawHistory.setUserId(userId);
    Page<WithdrawHistory> data=withdrawHistoryService.allPage(withdrawHistory);
    
		return new ObjectDataResponse<Page<WithdrawHistory>>(data);
	}
	
	public static void main(String[] args) {
		
		System.out.println(getRandom()); 
	} 
	
	@IgnoreAuth
	@ApiOperation(value = "提现说明查询", notes = "提现说明查询")
	@RequestMapping(value = "withContent", method = RequestMethod.POST)
	@ResponseBody
	private Response withContent(@CurrentUserId Long userId,@RequestBody WithdrawConfig withdrawConfig) {
		
		 List<WithdrawConfig> data=withdrawConfigService.find(withdrawConfig);
		 
		 User user=new User();
		 user.setId(userId);
		 List<User> userList=userService.find(user);
		 
		 if (data.size()>0) {
			 WithdrawConfig with=data.get(0);
			 if (userList.size()>0) {
				with.setCanWithdrawBalance(userList.get(0).getCanWithdrawBalance());
			 }
			 return ResponseUtil.ok(data.get(0));
		 }
		 return ResponseUtil.ok(withdrawConfig);
	}
	
	
	@IgnoreAuth
	@ApiOperation(value = "提现记录添加", notes = "提现记录添加")
	@RequestMapping(value = "withInsert", method = RequestMethod.POST)
	@ResponseBody
	private Response withInsert(@CurrentUserId Long userId,@RequestBody WithdrawHistory withdrawHistory) {
		WithdrawConfig con=new WithdrawConfig();
		List<WithdrawConfig> conList=withdrawConfigService.find(con);

		withdrawHistory.setUserId(userId);
		Long count=withdrawHistoryDao.getMaxCount(withdrawHistory);
		
		if (conList.size()>0) {
			WithdrawConfig config=conList.get(0);
			
			//今日提现次数拦截
			if (count.intValue()>=config.getMaxCount()) {
				return ResponseUtil.ok(3);
			}
			
			//今日提现金额拦截
			if(withdrawHistory.getAmount()<config.getMinAmount()){
				return ResponseUtil.ok(2);
			}
		}
		
		BankAccount bank=new BankAccount();
		bank.setId(withdrawHistory.getId());
		List<BankAccount> bankList=bankAccountService.find(bank);
		if (bankList.size()>0) {
			BankAccount account=bankList.get(0);
			withdrawHistory.setBankType(account.getBankId().intValue());
			withdrawHistory.setAccountType(1);
			withdrawHistory.setAccount(account.getCardNo());
		}
		
		User user=new User();
		user.setId(userId);
		List<User> userList=userService.find(user);
		if (userList.size()>0) {
			User u=userList.get(0);
			withdrawHistory.setName(u.getNickname());
			withdrawHistory.setPhone(u.getPhone());
		}
		withdrawHistory.setWithNum(getRandom());
		withdrawHistory.setUserId(userId);
		withdrawHistory.setStatus(1);
		Timestamp now = new Timestamp(System.currentTimeMillis()); 
		withdrawHistory.setCreateTime(now);
		withdrawHistory.setHandleTime(now);
		boolean flag=withdrawHistoryService.insert(withdrawHistory);
		int f=0;
		float res=0;
		if (flag==true) {
		    f=1;
		    if ( userList.size()>0) {
		    	User user3=userList.get(0);
		    	if (user3.getCanWithdrawBalance() >= withdrawHistory.getAmount()) {
		    		res=user3.getCanWithdrawBalance()-withdrawHistory.getAmount();
		    		
		    		User user2=new User();
		    		user2.setId(userId);
		    		user2.setCanWithdrawBalance(res);
		    		user2.setSuccessWithdrawBalance(user3.getSuccessWithdrawBalance()+withdrawHistory.getAmount());
		    		userService.update(user2);
				}
		    	
			}
	    
			//生成消息
			Message message = new Message();
			message.setUserId(userId);
			message.setType(1);
			message.setPushType(1);
			
			message.setContent("你已成功提交"+withdrawHistory.getAmount()+"元提现申请，请等待结果！");
			
			message.setCreateTime(new Timestamp(new Date().getTime()));
			message.setTitle("用户提现");
			message.setRemark("用户提现");
			//推送消息
			messageService.insert(message);
			
			//极光推送
			try {
				MsgPushUtils.addJPush(message.getContent(), userId.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
	   
	   }
	
	   return ResponseUtil.ok(f);
	}
	
	public static String getRandom(){
		String randomStr="";
		for (int i = 0; i < 9; i++) {
			int random=(int)(Math.random()*9);
			if(randomStr.indexOf(random+"")!=-1){
			  i=i-1;
			}else{
			  randomStr+=random;
			}
		}
		return randomStr;
	}
	
   
}
